<?php

namespace app\admin\controller\jy;

use Endroid\QrCode\Exception\InvalidPathException;
use karsonzhang\fastadmin\qrcode\library\QrCode;
use app\common\controller\Backend;
use think\Config;
use think\Db;
use think\Env;
use think\Exception;
use think\exception\DbException;
use think\exception\HttpResponseException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Response;

/**
 * 产品管理
 * @icon fa fa-circle-o
 */
class Product extends Backend
{
    /**
     * Product模型对象
     * @var \app\admin\model\jy\Product
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\jy\Product;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
//                ->with(['series', 'color'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
//                $row->visible(['id', 'product_name', 'series_id', 'cover_images', 'effect_images', 'description', 'scan_count', 'scan_user_count', 'share_count', 'share_user_count', 'praise_count', 'praise_user_count', 'download_count', 'download_user_count', 'weigh', 'status', 'create_time', 'update_time']);
//                $row->visible(['series']);
//                $row->getRelation('series')->visible(['id', 'series_name']);
//                $row->visible(['color']);
//                $row->getRelation('color')->visible(['id', 'color_name']);
//                $row->visible(['id', 'product_name', 'surface', 'color', 'lines', 'specs', 'place', 'cover_images', 'effect_images', 'weigh', 'status', 'create_time', 'update_time']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     * @return string
     * @throws Exception
     */
    public function add(): string
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if (!$params) {
                $this->error(__('Parameter %s can not be empty', ''));
            }
            $params = $this->preExcludeFields($params);
//            // 参数校验
//            if ($params['product_design'] == '[]' || $params['product_design'] == '') {
//                $this->error(__('案例不能为空'));
//            }
            Db::startTrans();
            try {
                $params['create_user'] = $this->auth->id;
                $result = $this->model->allowField(true)->save($params);
                if (!$result) {
                    Db::rollback();
                    $this->error(__('No rows were inserted'));
                }
                $designList = json_decode($params['product_design'], true);
                foreach ($designList as $index => &$design) {
                    $design['weigh'] = $index;
                    $design['product_id'] = $this->model->id;
                    $design['create_user'] = $this->auth->id;
                }
                model('app\admin\model\jy\ProductDesign')->saveAll($designList);
                Db::commit();
                $this->success();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        $this->view->assign('getProductDesignTpl', self::getProductDesignTpl());
        return $this->view->fetch();
    }

    /**
     * 编辑
     * @param null $ids
     * @return string
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit($ids = null): string
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
//                // 参数校验
//                if ($params['specs_image'] == '[]' || $params['specs_image'] == '') {
//                    $this->error(__('规格图不能为空'));
//                }
                Db::startTrans();
                try {
                    $result = $row->allowField(true)->save($params);
                    if (!$result) {
                        Db::rollback();
                        $this->error(__('No rows were updated'));
                    }
                    $designList = json_decode($params['product_design'], true);
                    foreach ($designList as $index => &$design) {
                        $design['weigh'] = $index;
                        $design['product_id'] = $row['id'];
                        $design['create_user'] = $this->auth->id;
                    }
                    model('\app\admin\model\jy\ProductDesign')->where(['product_id' => $row['id']])->delete();
                    model('\app\admin\model\jy\ProductDesign')->saveAll($designList);
                    Db::commit();
                    $this->success();
                } catch (ValidateException|Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $row['designJson'] = json_encode(
            model('\app\admin\model\jy\ProductDesign')
                ->where(['product_id' => $row['id'], 'is_del' => 0])
                ->order('weigh', 'asc')->select());
        $this->view->assign('getProductDesignTpl', self::getProductDesignTpl());
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * @throws DbException
     * @throws Exception
     * @throws InvalidPathException
     */
    // 生成二维码
    public function qrcode($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $config = get_addon_config('qrcode');
        if (isset($config['limitreferer']) && $config['limitreferer']) {
            $referer = $this->request->server('HTTP_REFERER', '');
            $refererInfo = parse_url($referer);
            $refererHost = $referer && $refererInfo ? $refererInfo['host'] : '';
            $refererHostArr = explode('.', $refererHost);
            $wildcardDomain = '';
            if (count($refererHostArr) > 2) {
                $refererHostArr[0] = '*';
                $wildcardDomain = implode('.', $refererHostArr);
            }
            $allowRefererList = $config['allowrefererlist'] ?? '';
            $domainArr = explode("\n", str_replace("\r", "", $allowRefererList));
            $domainArr = array_filter(array_unique($domainArr));
            $domainArr[] = request()->host(true);

            $inAllowList = false;

            if (in_array('*', $domainArr) || ($refererHost && in_array($refererHost, $domainArr)) || ($wildcardDomain && in_array($wildcardDomain, $domainArr))) {
                $inAllowList = true;
            }

            if (!$inAllowList && (!$referer && $config['allowemptyreferer'])) {
                $inAllowList = true;
            }

            if (!$inAllowList) {
                $response = Response::create('暂无权限', 'html', 403);
                throw new HttpResponseException($response);
            }
        }
        $params = $this->request->get();
        $params = array_intersect_key($params, array_flip(['text', 'size', 'padding', 'errorlevel', 'foreground', 'background', 'logo', 'logosize', 'logopath', 'label', 'labelfontsize', 'labelalignment']));

        $params['text'] = Env::get('project.mp_url') . '/productInfo?id=' . $row['id'];
        $params['label'] = '';

        $qrCode = \addons\qrcode\library\Service::qrcode($params);

        // 写入到文件
        $path = '';
        $file = '';
        if ($config['writefile']) {
            // 写入到文件
            $path = '/uploads/qrcode/';
            $qrcodePath = ROOT_PATH . 'public' . $path;
            if (!is_dir($qrcodePath)) {
                @mkdir($qrcodePath);
            }
            $file = md5(implode('', $params)) . '.' . $config['format'];
            if (is_really_writable($qrcodePath)) {
                $filePath = $qrcodePath . $file;
                $qrCode->writeFile($filePath);
            }
        }

        $row['qrcode'] = cdnurl($path . $file);
        $this->view->assign("row", $row);
        $this->assignconfig('productId', $row['id']);
        return $this->view->fetch();
    }

    public function addPrintNum($ids = "")
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        // 增加打印次数
        $data['print_num'] = $row['print_num'] + 1;
//        $data['update_time'] = date('Y-m-d H:i:s', time());
        $data['update_user'] = (int)$this->auth->id;
        $this->model->save($data, ['id' => $row['id']]);
        $this->success(__('Success'));
    }

    /**
     * 删除
     * @param string $ids
     * @throws \think\exception\DbException
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                model('\app\admin\model\jy\ProductDesign')
                    ->whereIn('product_id', $ids)
                    ->delete();
                model('\app\admin\model\jy\DesignProduct')
                    ->whereIn('product_id', $ids)
                    ->delete();
                model('\app\admin\model\jy\ProductSpecs')
                    ->whereIn('product_id', $ids)
                    ->delete();
                model('\app\admin\model\jy\ProductPraise')
                    ->whereIn('product_id', $ids)
                    ->delete();
                model('\app\admin\model\jy\ProductScan')
                    ->whereIn('product_id', $ids)
                    ->delete();
                model('\app\admin\model\jy\ProductShare')
                    ->whereIn('product_id', $ids)
                    ->delete();
                model('\app\admin\model\jy\ProductDownload')
                    ->whereIn('product_id', $ids)
                    ->delete();
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 获取操作模板
     * @return string
     */
    private function getProductDesignTpl(): string
    {
        $inputStr = '<input id="c-design_title" data-rule="required" class="form-control name-input" name="<%=name%>[<%=index%>][design_title]" type="text" maxlength="20"
                   value="<%=row[\'design_title\']%>">';
        $uploadId = 'design_images_<%=index%>';
        $uploadName = '<%=name%>[<%=index%>][design_images]';
        $tpl = '<dd class="form-inline">'
            . $inputStr
            . '<input type="text" id="c-' . $uploadId . '" name="' . $uploadName . '" class="form-control" value="<%=row[\'design_images\']%>" size="25">'
            . '<div class="input-group-addon no-border no-padding form-control">'
            . '<span><button type="button" id="plupload-' . $uploadId . '" class="btn btn-danger plupload" data-input-id="c-' . $uploadId . '" data-mimetype="image/gif,image/jpeg,image/png,image/jpg,image/bmp" data-multiple="true" data-preview-id="p-' . $uploadId . '"><i class="fa fa-upload"></i>' . __('Upload') . '</button></span>'
            . '<span class="image-choose"><button type="button" id="fachoose-' . $uploadId . '" class="btn btn-primary fachoose" data-input-id="c-' . $uploadId . '" data-mimetype="image/*" data-multiple="true"><i class="fa fa-list"></i>' . __('Choose') . '</button></span>'
            . '</div>'
            . '<span class="btn btn-sm btn-danger btn-remove"><i class="fa fa-times"></i></span>'
            . '<span class="btn btn-sm btn-primary btn-dragsort"><i class="fa fa-arrows"></i></span>'
            . '<span class="msg-box n-right" for="c-' . $uploadName . '"></span>'
            . '<ul class="row list-inline plupload-preview" id="p-' . $uploadId . '"></ul>'
            . '</dd>';
        return $tpl;
    }

    /**
     * 获取操作模板
     * @return string
     */
    private function getProductSpecsTpl(): string
    {
        $inputStr = '<input id="c-specs_title" data-rule="required" class="form-control name-input" name="<%=name%>[<%=index%>][specs_title]" type="text" maxlength="20"
                   value="<%=row[\'specs_title\']%>">';
        $uploadId = 'specs_images_<%=index%>';
        $uploadName = '<%=name%>[<%=index%>][specs_images]';
        $tpl = '<dd class="form-inline">'
            . $inputStr
            . '<input type="text" id="c-' . $uploadId . '" name="' . $uploadName . '" class="form-control" value="<%=row[\'specs_images\']%>" size="25">'
            . '<div class="input-group-addon no-border no-padding form-control">'
            . '<span><button type="button" id="plupload-' . $uploadId . '" class="btn btn-danger plupload" data-input-id="c-' . $uploadId . '" data-mimetype="image/gif,image/jpeg,image/png,image/jpg,image/bmp" data-multiple="false" data-preview-id="p-' . $uploadId . '"><i class="fa fa-upload"></i>' . __('Upload') . '</button></span>'
            . '<span class="image-choose"><button type="button" id="fachoose-' . $uploadId . '" class="btn btn-primary fachoose" data-input-id="c-' . $uploadId . '" data-mimetype="image/*" data-multiple="false"><i class="fa fa-list"></i>' . __('Choose') . '</button></span>'
            . '</div>'
            . '<span class="btn btn-sm btn-danger btn-remove"><i class="fa fa-times"></i></span>'
            . '<span class="btn btn-sm btn-primary btn-dragsort"><i class="fa fa-arrows"></i></span>'
            . '<span class="msg-box n-right" for="c-' . $uploadName . '"></span>'
            . '<ul class="row list-inline plupload-preview" id="p-' . $uploadId . '"></ul>'
            . '</dd>';
        return $tpl;
    }

    public function profile()
    {
        if ($this->request->isAjax()) {
            $list = [];
            $site = Config::get('site');
            $spaceList = $site['spaceList'];
            $total = count($spaceList);
            foreach ($spaceList as $a => $k) {
                $list[] = ['id' => $a, 'name' => $k];
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    private function getAddProfileValue()
    {
        $templateList = model('\app\admin\model\jy\ProductTemplate')->where(['is_del' => 0])->order('weigh desc')->find();
        $templateArr = json_decode($templateList['template_json'], true);
        $profile = [];
        foreach ($templateArr as $t) {
            if (substr($t['value'], 0, 2) === 'A:') {
                $arr = explode('|', substr($t['value'], 2, strlen($t['value']) + 1));
                $profile[] = [
                    'title'   => $t['title'],
                    'content' => isset($arr[0]) ? $arr[0] : '',
                    'arr'     => $arr,
                    'type'    => 'A'
                ];
            } else {
                $profile[] = [
                    'title'   => $t['title'],
                    'content' => $t['value'],
                    'arr'     => [],
                    'type'    => 'S'
                ];
            }
        }
        return json_encode($profile, JSON_UNESCAPED_UNICODE);
    }

    private function getEditProfileValue($profileJson)
    {
        if ($profileJson == '') return '';
        $templateList = model('\app\admin\model\jy\ProductTemplate')->where(['is_del' => 0])->order('weigh desc')->find();
        $templateArr = json_decode($templateList['template_json'], true);
        $template = [];
        foreach ($templateArr as $t) {
            if (substr($t['value'], 0, 2) === 'A:') {
                $template[$t['title']] = explode('|', substr($t['value'], 2, strlen($t['value']) + 1));
            } else {
                $template[$t['title']] = $t['value'];
            }
        }

        $profile = json_decode($profileJson, true);
        foreach ($profile as &$p) {
            if (isset($template[$p['title']]) && is_array($template[$p['title']])) {
                $p['type'] = 'A';
                $p['arr'] = $template[$p['title']];
            } else {
                $p['type'] = 'S';
                $p['arr'] = [];
            }
        }
        return json_encode($profile, JSON_UNESCAPED_UNICODE);
    }

    private function resetProfileValue($profileJson)
    {
        if ($profileJson == '') return '';
        $profile = json_decode($profileJson, true);
        $resetProfile = [];
        foreach ($profile as $p) {
            $resetProfile[] = [
                'title'   => $p['title'],
                'content' => $p['content']
            ];
        }
        return json_encode($resetProfile, JSON_UNESCAPED_UNICODE);
    }

}
